// index.js
// 获取应用实例
const app = getApp();
const {
  APPID,
  SECRET,
  MCHID
} = require("../../utils/util");

Page({
  data: {
    list: [],
    cates: [],
    toView: "view1",
    currentCategory: 0,
    isFixed: false,
    foods: [],
    isShowJiesuan: false,
    mockFoods: [],
    mockFoodsDetail: [],
    isShowTotal: false,
    store: "1",
    isFirstLoad: true
  },
  onLoad: async function (options) {

    await app.initMockShow()

    console.log(app.isShowTotal, 'isShowTotal');
    

    this.setData({
      store: options.store || '1',
    })
    app.store = this.data.store
    if (options.store === '1') {
      app.shopName = '上高味好佳鸡排店'
    } else {
      app.shopName = '左记甜品'
    }

    // if (options.from && options.from === 'code') {
    try {
      app.order.clear()
      app.order.list = []
    } catch (error) {
      console.log(error);

    }
    // }

    this.setData({
      isShowTotal: app.isShowTotal
    })

    // await this.getFoods();
    await this.initFoodList()

    this.getMockData();
  },
  onShow: async function () {
    // 如果开启了线上
    if (!this.data.isFirstLoad) {
      await this.initFoodList()
      return
    } else {
      console.log('第一次加载 此方法不执行');
    }
  },
  async initFoodList() {
    this.setData({
      isFirstLoad: false
    })
    console.log("onShow", this.data.store);
    if (this.data.foods.length <= 0 || app.order.list.length == 0) {
      await this.getFoods();
    }
    console.log(app.order.list, "app.order.list");
    let list = app.order.list;
    let foods = this.data.foods;
    console.log(foods, "foods");

    foods.forEach((item) => {
      if (item.list) {
        item.list.forEach(async (item3) => {
          list.forEach((item2) => {
            if (item3.id == item2.id) {
              item3['count'] = item2.count;
            }
          });
        });
      } else {
        item.list = [];
      }
    });
    this.setData({
      foods,
    });
  },
  async getFoods() {
    console.log("onload");
    const res = await app._http({
      url: "food/getlistwithcate",
      data: {
        store: this.data.store
      }
    });
    if (res.data.code === 1) {
      let totalFoods = res.data.foods;
      this.setData({
        hots: totalFoods.length > 0 ? totalFoods[0].list : [],
        foods: totalFoods,
        cates: res.data.cates,
      });
    }
  },
  gotoView(e) {
    const {
      index
    } = e.currentTarget.dataset;
    this.setData({
      toView: `view${index}`,
      currentCategory: index,
    });
  },
  ordergoods(e) {
    const {
      item
    } = e.currentTarget.dataset;
    app.order.add(item);
    console.log(app.order.list);

    let list = this.data.foods;
    list.forEach((li) => {
      if (li.catid == item.catid) {
        li.list.forEach((ilitem) => {
          if (ilitem.id == item.id) {
            console.log("找到了");
            if (ilitem.count) {
              ilitem.count++;
            } else {
              ilitem.count = 1;
            }
          }
        });
      }
    });
    this.setData({
      foods: list,
    });
  },
  decrementgoods(e) {
    const {
      item
    } = e.currentTarget.dataset;
    app.order.delete(item);

    let list = this.data.foods;
    list.forEach((li) => {
      if (li.catid == item.catid) {
        li.list.forEach((ilitem) => {
          if (ilitem.id == item.id) {
            if (ilitem.count >= 1) {
              ilitem.count--;
            }
          }
        });
      }
    });
    console.log(list.length, "length");

    this.setData({
      foods: list,
    });
  },

  gotodetail(e) {
    const {
      id
    } = e.currentTarget.dataset
    wx.navigateTo({
      url: '/pages/cpudetail/cpudetail?id=' + id,
    })
  },

  gotocate(e) {
    const {
      id
    } = e.currentTarget.dataset
    wx.navigateTo({
      url: '/pages/mfoodslist/mfoodslist?id=' + id,
    })
  },

  async gobuy() {
    console.log(app.globalData.userinfo);
    let userinfo = wx.getStorageSync("logininfo");
    let isLogin = wx.getStorageSync("isLogin");

    if (isLogin && userinfo.openid) {
      wx.navigateTo({
        url: "/pages/shop/shop",
      });
    } else {
      wx.showModal({
        content: "请登录",
        confirmColor: app.PCOLOR,
        success: (res) => {
          if (res.confirm) {
            wx.switchTab({
              url: "/pages/mine/mine",
            });
          }
        },
      });
    }

    // wx.switchTab({
    //   url: '/pages/shop/shop',
    // })
  },

  async initMockData() {
    const res = await app._http({
      url: 'food/getmockfood'
    })
    console.log(res, 'res');

    app.mockDatas = res.data.data
    app.mockFoodsDetail = res.data.cates
  },

  async getMockData() {
    await this.initMockData()
    this.setData({
      mockFoods: [{
          id: 1,
          name: "家常菜",
          img: "https://i2.chuimg.com/725b1e52088c4d88956e4f205b6936df_1080w_1414h.jpg?imageView2/1/w/640/h/520/q/90/format/jpg",
        },
        {
          id: 2,
          name: "快手菜",
          img: "https://img0.baidu.com/it/u=1958667538,2781405065&fm=26&fmt=auto",
        },
        {
          id: 3,
          name: "下饭菜",
          img: "https://img2.baidu.com/it/u=1811800581,583754986&fm=26&fmt=auto",
        },
        {
          id: 4,
          name: "早餐",
          img: "https://img2.baidu.com/it/u=361026219,1234747656&fm=26&fmt=auto",
        },
        {
          id: 5,
          name: "肉",
          img: "https://img1.baidu.com/it/u=2212265729,147424284&fm=26&fmt=auto",
        },
        {
          id: 6,
          name: "鱼",
          img: "https://img1.baidu.com/it/u=1863341932,2511277205&fm=26&fmt=auto",
        },
      ],
    });

    // setTimeout(() => {
    this.setData({
      mockFoodsDetail: app.mockFoodsDetail
    })
    // }, 2000);
  },
  gotoshop() {
    wx.navigateTo({
      url: '/pages/orders/orders',
    })
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return {
      title: '您的好友邀请您来点单~',

    }
  }
});